const pool = require('../config/database');

// 通用分页解析
function parsePagination(query) {
  const page = Math.max(parseInt(query.page || '1', 10), 1);
  const pageSize = Math.min(Math.max(parseInt(query.pageSize || '10', 10), 1), 100);
  const offset = (page - 1) * pageSize;
  return { page, pageSize, offset };
}

// 列表
async function listSoftware(query) {
  const { page, pageSize, offset } = parsePagination(query);
  const where = [];
  const params = [];

  if (query.category && query.category !== '') {
    where.push('category = ?');
    params.push(query.category);
  }
  if (query.status && query.status !== '') {
    where.push('status = ?');
    params.push(query.status);
  }
  const whereSQL = where.length ? ('WHERE ' + where.join(' AND ')) : '';

  const [rows] = await pool.query(
    `SELECT SQL_CALC_FOUND_ROWS id,name,category,size_bytes,downloads,rate,status,icon_url,description,created_at,updated_at
     FROM software_items ${whereSQL}
     ORDER BY created_at DESC
     LIMIT ? OFFSET ?`, [...params, pageSize, offset]
  );
  const [totalRows] = await pool.query('SELECT FOUND_ROWS() as total');
  return { list: rows, total: totalRows[0]?.total || 0, page, pageSize };
}

// 详情
async function getSoftware(id) {
  const [rows] = await pool.query(
    `SELECT id,name,category,size_bytes,downloads,rate,status,icon_url,description,created_at,updated_at
     FROM software_items WHERE id = ?`, [id]
  );
  return rows[0] || null;
}

// 创建软件
async function createSoftware(payload) {
  const { name, category, status = '已上线', description = '', icon_url = null } = payload;
  const size_bytes = Number(payload.size_bytes || 0);
  const downloads = Number(payload.downloads || 0);
  const rate = Number(payload.rate || 0);

  const [ret] = await pool.query(
    `INSERT INTO software_items (name,category,size_bytes,downloads,rate,status,icon_url,description)
     VALUES (?,?,?,?,?,?,?,?)`,
    [name, category, size_bytes, downloads, rate, status, icon_url, description]
  );
  return await getSoftware(ret.insertId);
}

// 软件文件列表
async function listFiles(softwareId) {
  const [rows] = await pool.query(
    `SELECT id,software_id,file_name,file_path,file_size,file_type,created_at
     FROM software_files WHERE software_id = ? ORDER BY created_at DESC`, [softwareId]
  );
  return rows;
}

// 为软件新增文件
async function addFile(softwareId, payload) {
  const { file_name, file_path, file_type = null } = payload;
  const file_size = Number(payload.file_size || 0);
  const [ret] = await pool.query(
    `INSERT INTO software_files (software_id,file_name,file_path,file_size,file_type)
     VALUES (?,?,?,?,?)`,
    [softwareId, file_name, file_path, file_size, file_type]
  );
  const [rows] = await pool.query(
    `SELECT id,software_id,file_name,file_path,file_size,file_type,created_at
     FROM software_files WHERE id = ?`, [ret.insertId]
  );
  return rows[0];
}

module.exports = {
  listSoftware,
  getSoftware,
  createSoftware,
  listFiles,
  addFile
};